package org.example.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.Entity.Remind;
import org.example.Mapper.RemindMapper;
import org.example.Service.RemindService;
import org.example.Utils.SendSmsUtil;
import org.example.Vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RemindServiceImpl extends ServiceImpl<RemindMapper, Remind> implements RemindService {

    @Autowired
    private RemindMapper remindMapper;

    @Override
    public void send() {
        LambdaQueryWrapper<Remind> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Remind::getOpen, 1);
        List<Remind> reminds = remindMapper.selectList(wrapper);
        for (Remind remind : reminds) {
            SendSmsUtil.sendSMS(remind.getPhone());
        }
    }

    @Override
    public R updateRemindUser(String phone) {
        LambdaQueryWrapper<Remind> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Remind::getPhone, phone);
        Remind remind = remindMapper.selectOne(wrapper);
        if (remind.getOpen() == 1) {
            remind.setOpen(0);
        } else {
            remind.setOpen(1);
        }
        remindMapper.updateById(remind);
        return R.ok("修改成功");
    }

    @Override
    public R getRemindUserStatus(String phone) {
        LambdaQueryWrapper<Remind> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Remind::getPhone, phone);
        Remind remind = remindMapper.selectOne(wrapper);
        if ( remind == null ) {
            Remind newRemindUser = new Remind();
            newRemindUser.setPhone(phone);
            newRemindUser.setOpen(0);
            remindMapper.insert(newRemindUser);
            return R.ok(0);
        }
        return R.ok(remind);
    }
}
